package srzy.module

import srzy.dao.DBUtil

object BureauDBComp extends AbsCaseDeal with srzy.common.Logging {

  val inMemorySource = DBUtil("InMemorySource")

  def deal = {

    val dbCompInfos = getCaseInfo.dbBureauCompInfos
    //    log.debug("dbCompInfos:" + dbCompInfos)
    for (dbCompInfo <- dbCompInfos) {
      try {
        //        log.debug("dbCompInfo:" + dbCompInfo)
        val para = dbCompInfo.para
        val arrPara: List[String] = {
          if (para.indexOf("#") == 0) {
            para.substring(1).split("#").toList
          } else {
            para.split("#").toList
          }
        }

        dbCompInfo.arrPara = arrPara
        logger.debug("Para:[" + dbCompInfo.para + "]")

        var sqlBinded = dbCompInfo.originalSQL
        for (j <- 0 until arrPara.length) {
          if (arrPara.apply(j).matches("[0-9]+")) {
            sqlBinded = sqlBinded.replaceFirst(":s" + (j + 1), arrPara.apply(j));
          } else {
            sqlBinded = sqlBinded.replaceFirst(":s" + (j + 1), "'" + arrPara.apply(j) + "'");
          }
        }
        logger.debug("sql:[" + dbCompInfo.originalSQL + "]")
        logger.debug("PreResult:[" + dbCompInfo.preResult + "]")

        dbCompInfo.assembledSQL = sqlBinded
        logger.debug("sqlBinded:[" + dbCompInfo.assembledSQL + "]")

        dbCompInfo.result = inMemorySource.executeLine(sqlBinded)
        logger.debug("result:[" + dbCompInfo.result + "]")

        if (!(dbCompInfo.preResult == dbCompInfo.result)) {
          dbCompInfo.compResult = false
          fail
        }
        logger.debug("CompResult:[" + dbCompInfo.compResult + "]")
      } catch {
        case ex: Exception => {
          logger.error(ex.getMessage(), ex)
          dbCompInfo.compResult = false
          fail
        }
      }

    }
  }
  def fail = {
    getCaseInfo.dbBureauCompResult = false
    getCaseInfo.caseResult = false
  }
}